import json
import os
import time
from datetime import datetime
from urllib.parse import urlencode

import requests


# from android_docker_api import AndroidDockerApi
# from main import MyBody, MyWindow
# from ikuai import IKuai


# utils.py
class DkGlobal:
    _instance = None
    window = None
    body = None
    android_docker = None
    ikuai = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(DkGlobal, cls).__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self):
        # 初始化全局类的状态
        pass


class HttpApi():
    def __init__(self, base_url, proxies_port=None):
        self.base_url = base_url
        if proxies_port == None and DkGlobal().window != None:
            proxies_port = DkGlobal().window.proxies_port.text()
        # 设置本地VPN代理
        if proxies_port:
            self.proxies = {
                'http': 'http://127.0.0.1:' + str(proxies_port),
                'https': 'http://127.0.0.1:' + str(proxies_port)  # https -> http
            }
        else:
            self.proxies = None
        # 设置其他项
        self.headers = {}
        self.cookies = {}

    def set_header(self, key, value):
        self.headers[key] = value

    def set_cookie(self, key, value):
        self.cookies[key] = value

    def get(self, endpoint, params=None):
        url = f"{self.base_url}/{endpoint}"
        response = requests.get(url, proxies=self.proxies, headers=self.headers, cookies=self.cookies, params=params)
        return response

    def post(self, endpoint, data=None, json=None):
        url = f"{self.base_url}/{endpoint}"
        response = requests.post(url, proxies=self.proxies, headers=self.headers, cookies=self.cookies, data=data,
                                 json=json)
        return response

    def put(self, endpoint, data=None, json=None):
        url = f"{self.base_url}/{endpoint}"
        response = requests.put(url, proxies=self.proxies, headers=self.headers, cookies=self.cookies, data=data,
                                json=json)
        return response

    def delete(self, endpoint):
        url = f"{self.base_url}/{endpoint}"
        response = requests.delete(url, proxies=self.proxies, headers=self.headers, cookies=self.cookies)
        return response


class ServerApi():
    def __init__(self):
        self.url = "https://independence.heiduoke.cn"
        self.auto_id = 3
        self.api = HttpApi(self.url)

    # 获取真机信息
    def get_devinfo(self):
        res = self.api.get("/gs_myt/api/getDevInfo?auto_id=" + str(self.auto_id))
        if (res.status_code == 200):
            return res.json()['data']
        else:
            return None

    # 获取小程序信息
    def get_appinfo(self, auto_id):
        res = self.api.get(f"/gs_myt/api/getApp?auto_id={auto_id}")
        if (res.status_code == 200):
            return res.json()['data']
        else:
            return None

    # 获取真机设备信息
    def get_android_devinfo(self, auto_id, app_id):
        res = self.api.get(f"/gs_myt/api/getAndroidDevinfo?auto_id={auto_id}&app_id={app_id}")
        if (res.status_code == 200):
            return res.json()['data']
        else:
            return None

    # 添加真机信息记录
    def set_devinfo_used(self, appinfo, devinfo):
        param = {
            "auto_id": appinfo['auto_id'],
            "app_id": appinfo['app_id'],
            "app_type": appinfo['app_type'],
            "devinfo_id": 0,
            "device_id": 0,
            # "devinfo_id": devinfo['devinfo_id'],
            # "device_id": devinfo['device_id'],
        }
        res = self.api.get(f"/gs_myt/api/addDevInfoUsed?{urlencode(param)}")
        if (res.status_code == 200):
            return res.json()['data']
        else:
            return None
        pass

    def set_devinfo_close(self, devinfo_id, remark):
        res = self.api.get(f"/gs_myt/api/setDevinfoClose?devinfo_id={devinfo_id}&remark={remark}")
        if (res.status_code == 200):
            return res.json()['data']
        else:
            return None

    def set_devinfo_error_count(self, devinfo_id):
        res = self.api.get(f"/gs_myt/api/setDevinfoErrorCount?devinfo_id={devinfo_id}")
        if (res.status_code == 200):
            return res.json()['data']
        else:
            return None

    def get_new_devinfo(self, auto_id):
        res = self.api.get(f"/gs_myt/api/getNewDevInfo?auto_id={auto_id}")
        if (res.status_code == 200):
            return res.json()['data']
        else:
            return None


def write_log(content, type='', file_name=''):
    if file_name != '':
        # 获取当前日期
        current_date = datetime.now().strftime("%Y%m%d")

        # 生成完整的文件名
        log_file_name = f"{file_name}.log"

        # 指定日志文件保存的目录
        log_directory = f"log/{current_date}"  # 假设日志文件保存在名为 "logs" 的目录下

        # 创建日志目录，忽略已存在的目录
        os.makedirs(log_directory, exist_ok=True)

        # 完整的日志文件路径
        log_file_path = os.path.join(log_directory, log_file_name)

        # 确保 content 是 unicode 字符串
        content = str(content).encode('utf-8').decode('utf-8')

        # 将日志内容追加到文件中
        with open(log_file_path, 'a', encoding='utf-8') as log_file:
            log_file.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} {type}: {content}\n")


def win_log(content, type='', file_name=''):
    datetime = time.strftime("%m-%d %H:%M:%S", time.localtime())
    content = f"{datetime} {content}"
    write_log(content, type, file_name)
    # print("content",content)
    # 打印日志内容
    body = DkGlobal().body
    if body is None:
        return False
    if type == 'error':
        # 添加项目到列表
        body.listWidgetError.addItem(str(content))
        # 检查并移除多余的项
        while body.listWidgetError.count() > 100:
            body.listWidgetError.takeItem(0)
    else:
        # 添加项目到列表
        body.listWidget.addItem(str(content))
        # 检查并移除多余的项
        while body.listWidget.count() > 100:
            body.listWidget.takeItem(0)

    return True


def getTestAndroid(id):
    list = {
        1: {'Names': '1a7951534df7dc4f09aac5b1e6f04617_1_T1001', 'State': 'running', 'data': '/mmc/data/data1_1723119922117', 'index': 1,
            'ip': '192.168.9.102', 'ADB': '192.168.9.102:5555', 'API': '192.168.9.102:9082', 'HOST_RPA': '192.168.9.101:7101',
            'RPC': '192.168.9.102:9083', 'SERVER_IP': '192.168.9.101', 'SERVER_PORT': '83', 'SERVER_HTTP': 'http://192.168.9.101:83',
            'status': '打开APP', 'time': 0, 'switch': True, 'Name': 'T1001', 'l2tp_id': 1},
        2: {'Names': '1a7951534df7dc4f09aac5b1e6f04617_2_T1002', 'State': 'running', 'data': '/mmc/data/data2_1725431242459', 'index': 2,
            'ip': '192.168.9.103', 'ADB': '192.168.9.103:5555', 'API': '192.168.9.103:9082', 'HOST_RPA': '192.168.9.101:7102',
            'RPC': '192.168.9.103:9083', 'SERVER_IP': '192.168.9.101', 'SERVER_PORT': '83', 'SERVER_HTTP': 'http://192.168.9.101:83',
            'status': '打开APP', 'time': 0, 'switch': True, 'Name': 'T1002', 'l2tp_id': 2,

            },
        3: {'Names': '1a7951534df7dc4f09aac5b1e6f04617_3_T1003', 'State': 'running', 'data': '/mmc/data/data3_1725431242830', 'index': 3,
            'ip': '192.168.9.104', 'ADB': '192.168.9.104:5555', 'API': '192.168.9.104:9082', 'HOST_RPA': '192.168.9.101:7103',
            'RPC': '192.168.9.104:9083', 'SERVER_IP': '192.168.9.101', 'SERVER_PORT': '83', 'SERVER_HTTP': 'http://192.168.9.101:83',
            'status': '打开APP', 'time': 0, 'switch': True, 'Name': 'T1003', 'l2tp_id': 3},
        4: {'Names': '1a7951534df7dc4f09aac5b1e6f04617_4_T1004', 'State': 'running', 'data': '/mmc/data/data4_1725888299056', 'index': 4,
            'ip': '192.168.9.105', 'ADB': '192.168.9.105:5555', 'API': '192.168.9.105:9082', 'HOST_RPA': '192.168.9.101:7104',
            'RPC': '192.168.9.105:9083', 'SERVER_IP': '192.168.9.101', 'SERVER_PORT': '83', 'SERVER_HTTP': 'http://192.168.9.101:83',
            'status': '写真机信息', 'time': 0, 'switch': True, 'Name': 'T1004', 'l2tp_id': 4}
    }
    return list[id]


def getDevinfoData(directory, delete=True):
    files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
    print(f"当前剩余：{len(files)}个-{directory}")
    if not files:
        return False
    # 假设我们处理第一个文件
    file_path = os.path.join(directory, files[0])
    try:
        # 打开并读取文件内容
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
        # 解析JSON数据
        return json.loads(content)
    except Exception as e:
        print("获取错误e:",e)
        if delete:
            print(f"错误导致删除文件{file_path}-{directory}")
            # 删除已读取的文件
            if os.path.exists(file_path):
                os.remove(file_path)
        return getDevinfoData(directory)
    finally:
        if delete:
            print(f"删除文件{file_path}")
            # 删除已读取的文件
            if os.path.exists(file_path):
                os.remove(file_path)


def getDeviceData():
    data = getDevinfoData("devinfo/oaid")
    device = {}
    if data is False:
        return False
    else:
        device['AndroidID'] = data['AndroidID']
        OAID = data['OAID']
        if OAID is None or OAID == "":
            OAID = data['GUID']
            if OAID is None or OAID == "":
                return getDeviceData()
        device['OAID'] = OAID
        return device


def getDevinfoAndOaid():
    res = {}
    res['devinfo'] = getDevinfoData("devinfo/data")
    res['device'] = getDeviceData()
    print("res", res)
    return res


if __name__ == '__main__':
    # server = ServerApi()
    # print(server.get_devinfo())
    # # current_timestamp = time.time()
    # # # 格式化时间戳为日期字符串
    # # current_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    # # print(current_date)
    # # res = ServerApi().get_devinfo()
    # # print(res)
    def parse_names(file_path):
        # 初始化字典
        data = {'男': set(), '女': set(), '未知': set()}

        # 读取文件
        with open(file_path, 'r', encoding='utf-8') as file:
            for line in file:
                parts = line.strip().split(',')
                if len(parts) == 2:
                    name, gender = parts
                    # 去掉名字的第一个字符（即姓氏）
                    name_without_surname = name[1:] if len(name) > 1 else ''
                    # 添加名字到对应性别的集合中，自动去重
                    data[gender].add(name_without_surname)

        return data


    def save_jsons(data, output_dir):
        # 创建输出目录（如果不存在）
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        # 遍历数据，并为每个性别创建一个单独的 JSON 文件
        for gender, names in data.items():
            output_path = os.path.join(output_dir, f"{gender}.json")

            # 将集合转为列表，并保存为JSON文件
            with open(output_path, 'w', encoding='utf-8') as json_file:
                json.dump(list(names), json_file, ensure_ascii=False, indent=4)

    # 指定输入文件路径
    input_file_path = 'log/namess.txt'
    # 指定输出目录路径
    output_directory = 'log/output_json_files'

    # 处理数据
    parsed_data = parse_names(input_file_path)
    # 保存数据到指定目录下的多个 JSON 文件
    save_jsons(parsed_data, output_directory)

    print(f"Data has been written to multiple JSON files in directory {output_directory}")